﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.Net;
using System.IO;

namespace DHT
{
    public class ListenServer
    {

        protected HttpListener Listener;
        protected bool IsStarted = false;

        //使用傳入一個URI String 例如http://127.0.0.1:8080/ 來開始一個我們的HttpServer
        public void Start(string strUrl)
        {
            if (IsStarted) //已經再Listen就直接Return
                return;

            if (Listener == null)
                Listener = new HttpListener();

            //使用傳入的URI String 例如http://127.0.0.1:8080/
            Listener.Prefixes.Add(strUrl);

            IsStarted = true;
            Listener.Start(); //開始Listen

            //以非同步方式取得Context
            IAsyncResult result = this.Listener.BeginGetContext(
              new AsyncCallback(WebRequestCallback), this.Listener);
        }

        //停止我們的HttpServer
        public void Stop()
        {
            if (Listener != null)
            {
                Listener.Close();
                Listener = null;
                IsStarted = false;
            }
        }

        //有個Web需求進來
        private void WebRequestCallback(IAsyncResult result)
        {
            //如果Http Server已經停止則不理會
            if (Listener == null)
                return;

            //取得Context
            HttpListenerContext Context = this.Listener.EndGetContext(result);

            //立即開始另一個非同步取得Context
            Listener.BeginGetContext(new AsyncCallback(WebRequestCallback), this.Listener);

            //處理我們的Web需求
            ProcessRequest(Context);
        }

        //處理我們的Web需求
        private void ProcessRequest(System.Net.HttpListenerContext Context)
        {
  
            HttpListenerResponse Response = Context.Response;
            Stream OutputStream = Response.OutputStream;

            //產生回傳的Byte Array
            byte[] bOutput = System.Text.Encoding.UTF8.GetBytes("<H1>Hello World!!!</H1>");

            //設定ContentType
            Response.ContentType = "text/html";

            //設定內容長度
            Response.ContentLength64 = bOutput.Length;

            //寫到Stream中
            OutputStream.Write(bOutput, 0, bOutput.Length);

            //關閉Stream
            OutputStream.Close();
        }
    }
}


